<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/6/13
 * Time: 15:38
 */

namespace app\modules\controllers;

use app\models\Profile;
use app\models\User;
use yii\data\Pagination;

class UserController extends CommonController
{
    public function actionUsers()
    {
        $model = User::find()->joinWith("profile");
        $userCount = $model->count();
        $pager = new Pagination(['totalCount' => $userCount,'pageSize' => \Yii::$app->params['pageSize']['user']]);
        $userList = $model->offset($pager->offset)->limit($pager->limit)->all();
        $this->layout = "layout1";
        return $this->render('users', ['users' => $userList, 'pager' => $pager]);
    }

    public function actionReg()
    {
        $this->layout = "layout1";
        $model = new User();
        if (\Yii::$app->request->isPost) {
            $data = \Yii::$app->request->post();
            if ($model->reg($data)) {
                \Yii::$app->session->setFlash("info","注册成功！");
            }
        }
        $model->userpass = '';
        $model->repass   = '';
        return $this->render('reg',['model' => $model]);
    }

    public function actionDel()
    {
      try {
          $userid = (int) \Yii::$app->request->get("userid");
          if (empty($userid)) {
              throw new \Exception();
          }
          $trans = \Yii::$app->db->beginTransaction();
          if ($obj = Profile::find()->where(['userid' => $userid])->one()) {
              $res = Profile::deleteAll(['userid' => $userid]);
              if (empty($res)) {
                  throw new \Exception();
              }
          }
          if (!User::deleteAll(['userid' => $userid])) {
              throw new  \Exception();
          }
          $trans->commit();
      } catch (\Exception $e) {
            if (\Yii::$app->db->getTransaction()) {
                $trans->rollBack();
            }
      }
        $this->redirect(['user/users']);

    }

}